// 依赖和基础信息
const ethers = require('ethers')
const Token = require('../Token.json')

const ganachePrivateKey =
  '0x700c472fef576757270df5068e0ec7152e7307000cfe3fbf5d15be43bde55230'
const ganacheAddress = '0xFBef33e09081236cC4A1f8D2C175E9fEf6Aa2DFa'

// 连接provider
let local_provider = new ethers.providers.JsonRpcProvider(
  'http://localhost:8545',
)

// 账户
let wallet = new ethers.Wallet(ganachePrivateKey)
console.log(`Loaded wallet ${wallet.address}`)

// 合约
const abi = Token.abi
const bytecode = Token.bytecode

const toEther = (value, decimals) => {
  if (!decimals) {
    decimals = 6
  }
  return ethers.utils.formatUnits(value, decimals)
}

// 查询余额方法
async function getTokenBalance(
  contractAddress,
  ganacheAddress,
  provider,
  enviroment,
) {
  let contract = new ethers.Contract(contractAddress, abi, provider)
  let balance = toEther(await contract.balanceOf(ganacheAddress))
  let decimals = await contract.decimals()
  let totalSupply = toEther(await contract.totalSupply())

  let symbol = await contract.symbol()
  let name = await contract.name()

  console.log(enviroment)
  console.log('====>balance:', balance)
  console.log('===>decimals:', decimals)

  console.log('====>all data:', {
    name,
    symbol,
    totalSupply,
    decimals,
    balance,
  })
  return balance
}

const USDT_mainnet = '0xdac17f958d2ee523a2206206994597c13d831ec7'
const USDT_natruelab = '0xb35DC76A99d9D7cb5c427a84349AdbE48757b7ac'

//查询
getTokenBalance(USDT_mainnet, ganacheAddress, local_provider, '本地环境')

getTokenBalance(USDT_natruelab, userAddress, naturelab_provider, 'naturelab')
